//
//  OAuthViewController.swift
//  ydy_weibo
//
//  Created by 杨德勇 on 16/7/15.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking



class OAuthViewController: UIViewController {
    let webView = UIWebView()
   

    //MARK:-
    //MARK:监听方法（导航控制器按钮的）
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fillAccount(){
        //让浏览器执行js代码
        let accountString = "document.getElementById('userId').value = '455428738@qq.com'"
        let pswSting = "document.getElementById('passwd').value = 'ydy13612595670'"
        webView.stringByEvaluatingJavaScriptFromString(accountString)
        webView.stringByEvaluatingJavaScriptFromString(pswSting)
        
        
    }
    
    
    
    //MARK:-
    //MARK:加载视图

    override func loadView() {
        view = webView
        webView.delegate = self
        setupUI()
        //加载网页
        loadOAuthPage()
    }
    
    //MARK:-
    //MARK:加载网页视图
    private func loadOAuthPage(){
        let urlstring = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        let url = NSURL(string: urlstring)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

    
    //MARK:-
    //MARK:view加载之后

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    
    }
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    private func setupUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(self.close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(self.fillAccount))
    }
    
    
    
    
}
//MARK:-
//MARK:发起网络请求并且获得权限，扩展继承，在这个大括号里专门处理代理


extension OAuthViewController:UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        guard let urlstr = request.URL?.absoluteString else{
            //获取URL，如果为空，不让访问
            return false
        }
        
        if urlstr.hasPrefix("https://api.weibo.com") {
            //判断是不是授权的页面，如果是，就让他执行
            return true
        }
        
        if !urlstr.hasPrefix(redirect_uri) {
            //判断是不是授权通过了，返回了我指定的页面，同时，屏蔽其他微博功能，
            return false
        }
        
        //程序到这里，肯定返回了我指定的页面，里面可能包含我的令牌（token）
        //url.query 是可以自动分析url中包涵的参数
        guard let query = request.URL?.query else{
            return false
        }
        
        let codePreFix = "code="
        let code = query.substringFromIndex(codePreFix.endIndex)
        
        UserAccountViewModel().loadAccessToken(code) { (error) in
            
            
            self.dismissViewControllerAnimated(true, completion: {
                
                
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
                
                print("切换到欢迎页面的通知已经发布")
                
            })
            
            
           
        }
        
        
        
        return false
    }
    
}